import {
  Divider, Form, FormInstance, Input, Radio
} from 'antd';
import { useEffect } from 'react';

import { useRequest } from 'ahooks';
import QuestionnaireSelect from './questionnaire-option';
import * as API from '../../../constants/api-constants';

interface BasicInfoProps {
  optionnalComponent: JSX.Element[] | undefined,
  templateTitle: string | undefined,
  questionnaireName: string | undefined,
  setQuestionnaireUuid: (questionnaireUuid: string) => void,
  basicInfo: AnswerSetting.UserBasicInitInfo | undefined,
  form: FormInstance<any>,
  isModify: boolean
}

export default ({
  optionnalComponent,
  templateTitle,
  questionnaireName,
  setQuestionnaireUuid,
  basicInfo,
  form,
  isModify
}: BasicInfoProps) => {
  useEffect(() => {
    form.setFieldsValue(basicInfo);
  }, [basicInfo]);

  useEffect(() => {
    form.resetFields();
  }, [templateTitle]);

  const { run, loading } = useRequest((tel: string) => ({
    url: API.EXIST_TEL,
    method: 'GET',
    params: { tel }
  }), {
    manual: true
  });

  // 自定义手机号校验规则
  const checkTel = (tel: string) => new Promise((resolve, reject) => {
    const reg = new RegExp(
      /^1([3578][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/
    );

    if (tel === undefined || tel === '') {
      reject(new Error('请填写手机号'));
      return;
    }

    if (reg.test(tel) === false) {
      reject(new Error('请填写正确的手机号'));
      return;
    }

    if (!isModify) {
      run(tel).then((result) => {
        if (result.data) {
          reject(new Error('手机号已被注册'));
        } else {
          resolve(result);
        }
      });

      return;
    }

    resolve('');
  });

  const checkEmail = (email?: string) => new Promise((resolve, reject) => {
    const reg = new RegExp(
      /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/
    );

    if (email === undefined || reg.test(email)) {
      resolve('');
      return;
    }

    reject(new Error('请填写正确的邮箱'));
  });

  return (
    <>
      <Divider orientation="left">基本信息</Divider>
      <Form
        form={form}
        initialValues={basicInfo}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
      >
        <QuestionnaireSelect
          templateTitle={templateTitle}
          questionnaireName={questionnaireName}
          setQuestionnaireUuid={setQuestionnaireUuid}
          isModify={isModify}
        />
        <Form.Item
          name="email"
          label="邮箱"
          validateTrigger={['onBlur']}
          rules={[
            {
              validator: (rule, value, callback) => {
                checkEmail(value).then(() => {
                  callback();
                })
                  .catch((error) => {
                    callback(error);
                  });
              },
              validateTrigger: 'onBlur'
            },
          ]}
        >
          <Input
            style={{ width: 350 }}
            onChange={(e) => {
              form.setFieldsValue({ email: e.target.value });
            }}
          />
        </Form.Item>
        <Form.Item
          name="tel"
          label="手机号"
          validateTrigger={['onBlur']}
          rules={[
            {
              validator: (rule, value, callback) => {
                checkTel(value).then(() => {
                  callback();
                })
                  .catch((error) => {
                    callback(error);
                  });
              },
              validateTrigger: 'onBlur'
            },
          ]}
        >
          <Input
            disabled={isModify || loading}
            style={{ width: 350 }}
            onChange={(e) => {
              form.setFieldsValue({ tel: e.target.value });
            }}
          />
        </Form.Item>
        <Form.Item
          name="gender"
          label="性别"
          rules={[
            {
              required: true,
              message: '请选择性别!',
            },
          ]}
        >
          <Radio.Group
            onChange={
              (e) => {
                form.setFieldsValue({ gender: e.target.value });
              }
            }
          >
            <Radio value={1}>男</Radio>
            <Radio value={2}>女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="maritalStatus"
          label="婚姻状况"
          rules={[
            {
              required: true,
              message: '请选择婚姻状况！',
            },
          ]}
        >
          <Radio.Group
            onChange={
              (e) => {
                form.setFieldsValue({ maritalStatus: e.target.value });
              }
            }
          >
            <Radio value={1}>已婚</Radio>
            <Radio value={0}>未婚</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="childrenSituation"
          label="子女情况"
          rules={[
            {
              required: true,
              message: '请选择子女情况！',
            },
          ]}
        >
          <Radio.Group
            onChange={
              (e) => {
                form.setFieldsValue({ childrenSituation: e.target.value });
              }
            }
          >
            <Radio value={1}>有</Radio>
            <Radio value={0}>无</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="age"
          label="年龄"
          rules={[
            {
              required: true,
              message: '请选择年龄！',
            },
          ]}
        >
          <Radio.Group
            onChange={
              (e) => {
                form.setFieldsValue({ age: e.target.value });
              }
            }
          >
            <Radio value={1}>20-30岁</Radio>
            <Radio value={2}>31-40岁</Radio>
            <Radio value={3}>41-50岁</Radio>
            <Radio value={4}>50岁以上</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="education"
          label="文化程度"
          rules={[
            {
              required: true,
              message: '请选择文化程度！',
            },
          ]}
        >
          <Radio.Group
            onChange={(e) => {
              form.setFieldsValue({ education: e.target.value });
            }}
          >
            <Radio value={1}>大专及以下</Radio>
            <Radio value={2}>本科</Radio>
            <Radio value={3}>硕士</Radio>
            <Radio value={4}>硕士以上</Radio>
          </Radio.Group>
        </Form.Item>
        {
          optionnalComponent?.map((item) => item)
        }
      </Form>

    </>
  );
};
